package com.threeonemeeting.task;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.list.FullMeetingInfoList;
import com.threeonemeeting.model.FullMeetingInfo;

// 获取热门会议列表
public class SearchMeetingTask extends ApplicationTask {

	public SearchMeetingTask(Context context, ICallBack callback) {
		super(context, callback);

		this.bCached = true;
		this.nTaskType = HttpConst.TASKTYPE_SEARCHMEETING;
		this.strUrl = "http://new.31huiyi.com/json/GetSearchEventListHandler.ashx";
	}

	// 具体的task实现该方法，对响应报文进行解析
	protected Map<String, Object> parseResponse(String strResponse) {

		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put(HttpConst.KEY_TASK_TYPE, nTaskType);
		mapData.put(HttpUtil.KEY_ERROR_CODE, HttpUtil.ERROR_SUCCESS);
		mapData.put(Const.Keys.KEY_PAGE, nCurrentPages);

		JSONObject jsonResp = null;
		try {
			jsonResp = new JSONObject(strResponse);
		} catch (Exception e) {
			setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
			return mapData;
		}

		try {
			// 获取 "Setting"部分的内容
			String strSuccess = jsonResp.getString("success");
			if (strSuccess == null) {
				setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
				return mapData;
			}

			if (strSuccess.equalsIgnoreCase("true") == false) {
				setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
				return mapData;
			}

			JSONArray dataJson = jsonResp.getJSONArray("data");
			if (dataJson == null) {
				setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
				return mapData;
			}

			FullMeetingInfoList list = new FullMeetingInfoList();
			for (int i = 0, n = dataJson.length(); i < n; i++) {

				JSONObject jData = dataJson.getJSONObject(i);

				FullMeetingInfo fullInfo = ProtocolHelper
						.getFullMeetingInfo(jData);
				if (fullInfo != null) {
					DataCenter.getInstance().listFullMeeting
							.addFullMeetingInfo(fullInfo);
					list.addFullMeetingInfo(fullInfo);
				}
				
			}

			mapData.put(Const.Keys.KEY_LIST, list);
			setErr(HttpUtil.ERROR_SUCCESS, mapData);
			return mapData;

		} catch (JSONException ex) {
			setErr(HttpUtil.ERROR_SERVER_PACKET, mapData);
			return mapData;
		}
	}
}
